package com.xinwei.leetcode.二叉树;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

// https://leetcode-cn.com/problems/binary-tree-level-order-traversal/
public class _102_二叉树的层序遍历 {
    public List<List<Integer>> levelOrder(TreeNode root) {
        // LinkedList类实现了Queue接口，因此我们可以把LinkedList当成Queue来用
        LinkedList<TreeNode> queue = new LinkedList<>();
        ArrayList<List<Integer>> lists = new ArrayList<>();
        if (root == null) return lists;
        ArrayList<Integer> list = new ArrayList<>();
        int row = 1;
        int height = 0;
        queue.offer(root);
        while (!queue.isEmpty()){
            TreeNode node = queue.poll();
            list.add(node.val);
            row--;
            if (node.left != null) {
                queue.offer(node.left);
            }
            if (node.right != null) {
                queue.offer(node.right);
            }
            if (row == 0) {
                row = queue.size();
                height++;
                lists.add(list);
                list = new ArrayList<Integer>();
            }
        }
        return lists;
    }
}
